package com.zhiwang.xiaoqu.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatTextView
import com.zhiwang.xiaoqu.R


class ColdDownTextView: AppCompatTextView {

    private val TAG = "ColdDownTextView"
    @ColorInt
    var idleTextColor: Int = 0
    @ColorInt
    var coldingTextColor: Int = 0
    var coldTime: Int = 0
    var unit: String? = null
    var idleText: String? = null

    var isCounting = false
    private var countingDownTimer: CountingDownTimer? = null


    constructor(context: Context, attrs: AttributeSet):super(context, attrs) {

        val array = context.obtainStyledAttributes(attrs, R.styleable.ColdDownTextView)
        idleText = array.getString(R.styleable.ColdDownTextView_idle_text)
        idleTextColor = array.getColor(R.styleable.ColdDownTextView_idle_text_color, Color.TRANSPARENT)
        coldingTextColor = array.getColor(R.styleable.ColdDownTextView_coldding_text_color, Color.WHITE)
        coldTime = array.getInt(R.styleable.ColdDownTextView_cold_time, 60)
        unit = array.getString(R.styleable.ColdDownTextView_unit)
        text = idleText
        setTextColor(idleTextColor)
        array.recycle()
    }


    fun start() {
        if (!isCounting) {
            countingDownTimer = CountingDownTimer((coldTime * 1000).toLong(), 1000)
            countingDownTimer!!.start()
            setTextColor(coldingTextColor)
        }
    }



    private inner class CountingDownTimer
    /**
     * @param millisInFuture    The number of millis in the future from the call
     * to [.start] until the countdown is done and [.onFinish]
     * is called.
     * @param countDownInterval The interval along the way to receive
     * [.onTick] callbacks.
     */
        (millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {

        init {
            isCounting = true
        }

        @SuppressLint("SetTextI18n")
        override fun onTick(millisUntilFinished: Long) {
            text = "${millisUntilFinished / 1000} $unit"
        }

        override fun onFinish() {
            isCounting = false
            setTextColor(idleTextColor)
            text = idleText
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (countingDownTimer != null)
            countingDownTimer!!.cancel()
    }
}